package com.wkbb.basic.controller.open;

import com.wkbb.basic.feign.TcCloudFeignService;
import com.wkbb.common.dto.basic.ClassInfo;
import com.wkbb.basic.model.Employee;
import com.wkbb.basic.service.ClassInfoService;
import com.wkbb.basic.service.FamilyService;
import com.wkbb.basic.service.TeacherManageService;
import com.wkbb.basic.service.UserOpenService;
import com.wkbb.basic.thread.*;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.ImRepairClassMasterDto;
import com.wkbb.common.utils.ThreadPoolUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dengjingyuan
 * @date 2019-07-29 10:49
 */
@Api(description = "Im相关接口")
@RestController
@RequestMapping("/basic/{apiVersion}/open")
@Slf4j
public class ImController {

    @Autowired
    private UserOpenService userOpenService;
    @Autowired
    private ClassInfoService classInfoService;
    @Autowired
    private TcCloudFeignService tcCloudFeignService;
    @Autowired
    private FamilyService familyService;
    @Autowired
    private TeacherManageService teacherManageService;



    @ApiOperation(value = "通过im账号获取当前用户的所有相关信息")
    @RequestMapping(value = "/getUserInfoByImAccount", method = RequestMethod.GET)
    public ResultDTO<Object> getUserInfoByImAccount(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "多个im账号ID,分号分割", required = true) @RequestParam(name = "imAccounts", required = true) String imAccounts
    ) {

        if (null == imAccounts) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        try {
            log.info("*************getUserInfoByImAccount**************imAccount:{}", imAccounts);
            return new ResultDTO<>(userOpenService.getUserInfoByImAccount(imAccounts));
        } catch (Exception e) {
            log.error("*************ImController getUserInfoByImAccount:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "此接口自动修复IM班级群(整个学校所有IM数据)")
    @RequestMapping(value = "/repairImAllInfo", method = RequestMethod.POST)
    public ResultDTO<Object> repairImAllInfo(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId
    ) {

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            log.info("*************ImController repairImAllInfo:{}**************apiVersion:{}", apiVersion);
            ThreadPoolUtil.addTask(new ImAutoClassIdByOrgIdTask(orgId, userOpenService));
            return new ResultDTO<Object>();
        } catch (Exception e) {
            log.error("*************ImController repairImAllInfo:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "此接口自动修复IM班级群群主功能")
    @RequestMapping(value = "/repairImClassGroupV2ImOwnerAccount", method = RequestMethod.POST)
    public ResultDTO<Object> repairImClassGroupV2ImOwnerAccount(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId
    ) {

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            log.info("*************ImController repairImClassGroupV2ImOwnerAccount:{}**************apiVersion:{}", apiVersion);
            ThreadPoolUtil.addTask(new ImChangeOwnerByOrgIdV2Task(orgId, userOpenService));
            return new ResultDTO<Object>();
        } catch (Exception e) {
            log.error("*************ImController repairImClassGroupV2ImOwnerAccount:{}**************", e);
        }
        return new ResultDTO<>();

    }

    @ApiOperation(value = "此接口自动修复IM群(只创建群)")
    @RequestMapping(value = "/repairImClassGroup", method = RequestMethod.POST)
    public ResultDTO<Object> repairImClassGroup(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId
    ) {

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {

            log.info("*************ImController repairImClassGroup:{}**************apiVersion:{}", apiVersion);
            ThreadPoolUtil.addTask(new ImRepairImClassGroupTask(orgId, userOpenService));
            return new ResultDTO<Object>();
        } catch (Exception e) {
            log.error("*************ImController repairImClassGroup:{}**************", e);
        }
        return new ResultDTO<>();

    }

    @ApiOperation(value = "此接口自动修复IM用户(包含群信息)")
    @RequestMapping(value = "/repairImClassGroupInfo", method = RequestMethod.POST)
    public ResultDTO<Object> repairImClassGroupInfo(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId
    ) {

        if (null == userId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            log.info("*************ImController repairImClassGroupInfo:{}**************apiVersion:{}", apiVersion);
            ThreadPoolUtil.addTask(new ImRepairImClassGroupInfoTask(userId,orgId, userOpenService));
            return new ResultDTO<Object>();
        } catch (Exception e) {
            log.error("*************ImController repairImClassGroupInfo:{}**************ImUserDto:{}", e);
        }
        return new ResultDTO<>();

    }

    @ApiOperation(value = "修复IM缺失班级群数据(1)")
    @RequestMapping(value = "/repairImClassGroupInfoALL", method = RequestMethod.POST)
    public ResultDTO<Object> repairImClassGroupInfoALL(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion
    ) {
        try {
            log.info("*************ImController repairImClassGroupInfoALL:{}**************apiVersion:{}", apiVersion);
            //查询所有有效班级
            List<Long> classIdList = classInfoService.getClassIdList();

            //查询IM所有已生成的有效班级集合
            ResultDTO<List<Long>> imClassInfo = tcCloudFeignService.getImClassInfo();
            if(ResultDTO.checkSuccess(imClassInfo)&& CollectionUtils.isNotEmpty(imClassInfo.getData())&&imClassInfo.getData().size()>0){
                classIdList.retainAll(imClassInfo.getData());
            }

            classInfoService.repairImClassGroupInfoALL(classIdList);
            //获取到所有未创建IM的班级,修复班级信息
            return new ResultDTO<Object>();
        } catch (Exception e) {
            log.error("*************ImController repairImClassGroupInfoALL:{}**************", e);
        }
        return new ResultDTO<>();

    }

    @ApiOperation(value = "修复未入群的家长(2),支持单个学校家长修复")
    @RequestMapping(value = "/repairFamilyIm", method = RequestMethod.POST)
    public ResultDTO<Object> repairFamilyIm(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId
    ) {
        try {
            log.info("*************ImController repairFamilyIm:{}**************apiVersion:{},orgId:{}", apiVersion,orgId);
            familyService.getRepairFamilyList(orgId);
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("*************ImController repairFamilyIm:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "修复未入群的园长(3)")
    @RequestMapping(value = "/repairMasterIm", method = RequestMethod.POST)
    public ResultDTO<Object> repairMasterIm(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion
    ) {
        try {
            log.info("*************ImController repairMasterIm:{}**************apiVersion:{}", apiVersion);
            //查询所有有效园长
            List<Long> employeeListAll = teacherManageService.getEmployeeListAll();


            //查询IM所有已入群的园长
            ResultDTO<List<Long>> imMasterList = tcCloudFeignService.getImMaster();
            if(ResultDTO.checkSuccess(imMasterList)&& CollectionUtils.isNotEmpty(imMasterList.getData())&&imMasterList.getData().size()>0){
                employeeListAll.retainAll(imMasterList.getData());
            }

            //查詢所有未入群的园长
            List<Employee> masterByUserIdList = teacherManageService.getMasterByUserIds(employeeListAll);
            if(CollectionUtils.isNotEmpty(masterByUserIdList)){
                for(Employee employee:masterByUserIdList){
                    ThreadPoolUtil.addTask(new ImRepairImClassGroupInfoTask(employee.getUserId(),employee.getOrgId(), userOpenService));
                }
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("*************ImController repairMasterIm:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "修复未入群的班主任和任课老师(4)")
    @RequestMapping(value = "/repairClassMaster", method = RequestMethod.POST)
    public ResultDTO<Object> repairClassMaster(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion
    ) {
        try {
            log.info("*************ImController repairClassMaster:{}**************apiVersion:{}", apiVersion);
            //查询所有班主任和任课老师
            log.info("----------查询所有班级的班主任和任课老师----------");
            List<ImRepairClassMasterDto> classInfoDtoList = classInfoService.getMasterAndTeacherCourseNum();

            ArrayList<Long> repairClassIdList = new ArrayList<>();
            //查询IM已入群的班主任和任课老师

            if(CollectionUtils.isNotEmpty(classInfoDtoList)){
                log.info("----------查询所有已入群的班主任和任课老师----------");
                ResultDTO<List<ImRepairClassMasterDto>> classMaster = tcCloudFeignService.getClassMasterNum();
                if(ResultDTO.checkSuccess(classMaster)&&null!=classMaster.getData()&&classMaster.getData().size()>0){
                    //对比班级里面数据不一致的数据记录班级
                    classInfoDtoList.forEach(e ->{
                        classMaster.getData().forEach(c ->{
                            if(e.getId().equals(c.getId())&&!e.getNum().equals(c.getNum())){
                                log.info("----------将相同班级ID并且NUM不一致的班级保存----------");
                                repairClassIdList.add(e.getId());
                            }
                        });
                    });

                    //通过有差异的班级获取所有班主任和任课老师
                    if(CollectionUtils.isNotEmpty(repairClassIdList)){
                        repairClassIdList.forEach(e->{
                            log.info("---------查询差异的班级获取所有班主任和任课老师-----------");
                            List<Long> employeeInfoDtoList = classInfoService.getMasterAndTeacherCourse(e);

                            try{
                                ClassInfo classInfo = classInfoService.getByPrimaryKey(e);
                                ArrayList<Long> allUserId = new ArrayList<>();
                                if(CollectionUtils.isNotEmpty(employeeInfoDtoList)){
                                    log.info("---------查询差异的班级获取已入群的所有班主任和任课老师-----------");
                                    ResultDTO<List<Long>> imEmployeeInfoDtoList = tcCloudFeignService.getImMasterAndTeacherCourse(e);
                                    if(ResultDTO.checkSuccess(imEmployeeInfoDtoList)&&CollectionUtils.isNotEmpty(imEmployeeInfoDtoList.getData())){
                                        log.info("---------获取全集-----------");
                                        allUserId.addAll(imEmployeeInfoDtoList.getData());
                                        allUserId.addAll(employeeInfoDtoList);
                                        log.info("---------获取交集-----------");
                                        employeeInfoDtoList.retainAll(imEmployeeInfoDtoList.getData());
                                        allUserId.removeAll(employeeInfoDtoList);
                                        log.info("---------已获取到补集-----------");

                                        allUserId.forEach(f->{
                                            ThreadPoolUtil.addTask(new ImRepairImClassGroupInfoTask(f,classInfo.getOrgId(), userOpenService));
                                        });
                                    }
                                }
                            }catch (Exception z){
                               log.error("---------修复用户数据异常----------");
                            }
                        });
                    }
                }
            }
            return new ResultDTO<>();
        } catch (Exception e) {
            log.error("*************ImController repairClassMaster:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "查询所有有效家长")
    @RequestMapping(value = "/getFamilyListAll", method = RequestMethod.GET)
    public ResultDTO<List<Long>> getFamilyListAll(
            @ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId
    ) {
        try {
            //查询所有有效家长
            return new ResultDTO<>(familyService.getFamilyListAll(orgId));
        } catch (Exception e) {
            log.error("*************ImController getFamilyList:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "查询所有有效园长")
    @RequestMapping(value = "/getEmployeeListAll", method = RequestMethod.GET)
    public ResultDTO<List<Long>> getEmployeeListAll(
    ) {
        try {
            //查询所有有效家长
            return new ResultDTO<>(teacherManageService.getEmployeeListAll());
        } catch (Exception e) {
            log.error("*************ImController getEmployeeListAll:{}**************", e);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "学生家长导入IM数据创建以入群(支持多个EXCLE导入)")
    @RequestMapping(value = "/repairFamilyExcle", method = RequestMethod.GET)
    public ResultDTO repairFamilyExcle(
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId
    ) {
        try {
            log.info("***********ImChatRepairController.repairFamilyExcle******,orgId:{}",orgId);
            familyService.getRepairFamilyList(orgId);
            return new ResultDTO();
        } catch (Exception e) {
            log.error("***********ImChatController.repairFamilyExcle******", e);
            return new ResultDTO(false);
        }
    }

    @ApiOperation(value = "定时器修复IM家长数据(一小时检测一次)")
    @RequestMapping(value = "/repairFamilyImTask", method = RequestMethod.POST)
    public ResultDTO repairFamilyImTask() {
        try {
            log.info("***********ImChatRepairController.repairFamilyImTask******");
            familyService.repairFamilyImTask();
            return new ResultDTO();
        } catch (Exception e) {
            log.error("***********ImChatController.repairFamilyImTask******", e);
            return new ResultDTO(false);
        }
    }
}
